const { UserType, Resource, MainMenu, MainMenuSubMenu, User } = require('../../database/index')
const { getExecutedSql } = require('../../logger');
const Sequelize = require('sequelize')
// 导出
module.exports = async (req, res) =>
{
    const operation = req.params.operation;
    const { description, userTypeID, resource, searchType, pageNum = 1, // 默认页码为1
        pageSize = 3, userTypeName } = req.body
    try {
        switch (operation) {
            case 'create':
                // // 根据客户端传递过来的 用户名 查询 数据库 中 是否 存在这用户名
                const state = {
                    UserTypeName: userTypeName,
                    Description: description,
                    Resources: "[1,2,3,4,5]"
                }
                const newUserTypeData = await UserType.create(state)
                const data = await UserType.findOne({
                    where: {
                        UserTypeID: newUserTypeData.UserTypeID
                    }
                })
                res.status(200).send({
                    data,
                    meta: {
                        msg: "创建成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'read':
                // 在这里实现获取用户列表的操作
                let whereCondition = {}; // 默认查询条件为空对象
                if (searchType === "exact" && userTypeName) {
                    // 执行精确搜索
                    whereCondition = { UserTypeName: { [Sequelize.Op.eq]: userTypeName } };
                } else if (searchType === "fuzzy" && userTypeName) {
                    // 执行模糊搜索
                    whereCondition = { UserTypeName: { [Sequelize.Op.like]: `%${userTypeName}%` } };
                }

                const total = await UserType.count({ where: whereCondition }); // 根据查询条件获取数据总数

                const offset = (pageNum - 1) * pageSize; // 计算偏移量

                const UserTypeData = await UserType.findAll({
                    where: whereCondition,
                    limit: Number(pageSize),
                    offset: Number(offset),
                });
                for (const item of UserTypeData) {
                    // 将 item.Resources 格式化为数组
                    const resources = JSON.parse(item.Resources);
                    item.Resources = {};
                    const mainMenus = {};

                    for (const ResourceID of resources) {
                        const subMenuList = await Resource.findOne({ where: { ResourceID: ResourceID } });
                        const mainMenuSubMenu = await MainMenuSubMenu.findOne({ where: { SubMenuID: subMenuList.ResourceID } });

                        if (mainMenuSubMenu) {
                            const mainMenu = await MainMenu.findOne({ where: { MenuID: mainMenuSubMenu.MainMenuID } });

                            if (mainMenu) {
                                const subMenuInfo = {
                                    ResourceID: subMenuList.ResourceID,
                                    ResourceName: subMenuList.ResourceName,
                                    ResourceType: subMenuList.ResourceType,
                                    Icon: subMenuList.Icon,
                                    Path: subMenuList.Path
                                };

                                // 创建主菜单的唯一键，这里使用 MainMenuID
                                const mainMenuKey = mainMenu.MenuID.toString();

                                // 如果主菜单已经存在，则将子菜单项合并到现有主菜单
                                if (mainMenus[mainMenuKey]) {
                                    mainMenus[mainMenuKey].SubMenuInfo.push(subMenuInfo);
                                } else {
                                    // 否则，创建新的主菜单项并添加到 mainMenus 中
                                    mainMenus[mainMenuKey] = {
                                        MainMenuID: mainMenu.MenuID,
                                        MainMenuName: mainMenu.MenuName,
                                        MainMenuIcon: mainMenu.Icon,
                                        MainMenuURL: mainMenu.URL,
                                        MainMenuOrder: mainMenu.Order,
                                        SubMenuInfo: [subMenuInfo]
                                    };
                                }
                            }
                        }
                    }
                    // 将 mainMenus 中的值转换为数组形式，以便重新赋值给 item.Resources
                    item.Resources = Object.values(mainMenus);
                }
                res.status(200).send({
                    data: {
                        total,
                        pageSize: Number(pageSize),
                        pageNum: Number(pageNum),
                        UserTypeData
                    },
                    meta: {
                        msg: "获取成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'findByName':
                // 根据UserName来查询用户
                const userType = await UserType.findOne({ where: { UserTypeName: userTypeName } })
                
                // 将 item.Resources 格式化为数组
                const resourcesItem = JSON.parse(userType.Resources);
                const mainMenusItem = [];
                for (const ResourceID of resourcesItem) {
                    const subMenuList = await Resource.findOne({ where: { ResourceID: ResourceID } });
                    const mainMenuSubMenu = await MainMenuSubMenu.findOne({ where: { SubMenuID: subMenuList.ResourceID } });
                    if (mainMenuSubMenu) {
                        const mainMenu = await MainMenu.findOne({ where: { MenuID: mainMenuSubMenu.MainMenuID } });
                        if (mainMenu) {
                            const subMenuInfo = {
                                ResourceID: subMenuList.ResourceID,
                                ResourceName: subMenuList.ResourceName,
                                ResourceType: subMenuList.ResourceType,
                                Icon: subMenuList.Icon,
                                Path: subMenuList.Path
                            };
                            // 创建主菜单的唯一键，这里使用 MainMenuID
                            const mainMenuKey = mainMenu.MenuID.toString() - 1;
                            // 如果主菜单已经存在，则将子菜单项合并到现有主菜单
                            if (mainMenusItem[mainMenuKey]) {
                                if (mainMenu.HasChild) {
                                    // 如果有子菜单，将子菜单项合并到现有主菜单
                                    mainMenusItem[mainMenuKey].SubMenuInfo.push(subMenuInfo);
                                } else {
                                    // 如果没有子菜单，将SubMenuInfo设置为null或空数组
                                    mainMenusItem[mainMenuKey].SubMenuInfo = null; // 或者可以设置为 []
                                }
                            } else {
                                // 创建新的主菜单项并根据HasChild设置SubMenuInfo
                                if (mainMenu.HasChild) {
                                    mainMenusItem[mainMenuKey] = {
                                        MainMenuID: mainMenu.MenuID,
                                        MainMenuName: mainMenu.MenuName,
                                        MainMenuIcon: mainMenu.Icon,
                                        MainMenuURL: mainMenu.URL,
                                        MainMenuOrder: mainMenu.Order,
                                        HasChild: mainMenu.HasChild,
                                        SubMenuInfo: [subMenuInfo] // 包含子菜单数据的数组
                                    };
                                } else {
                                    mainMenusItem[mainMenuKey] = {
                                        MainMenuID: mainMenu.MenuID,
                                        MainMenuName: mainMenu.MenuName,
                                        MainMenuIcon: mainMenu.Icon,
                                        MainMenuURL: mainMenu.URL,
                                        MainMenuOrder: mainMenu.Order,
                                        HasChild: mainMenu.HasChild,
                                        SubMenuInfo: null // 或者可以设置为 []
                                    };
                                }
                            }

                        }
                    }
                }
                // 使用 filter 方法过滤掉 null 元素
                userType.Resources = mainMenusItem.filter(element => { return element != null });

                res.status(200).send({
                    data: userType,
                    meta: {
                        msg: "获取成功",
                        status: 200
                    }
                });
                break;
            case 'update':
                const stateData = {
                    UserTypeName: userTypeName,
                    Description: description,
                    Resources: resource
                }
                const upUserTypeData = await UserType.update(stateData, { where: { userTypeID: userTypeID } },)
                const newTypeData = await UserType.findOne({ where: { userTypeID: userTypeID } });

                // 将 item.Resources 格式化为数组
                const resources = JSON.parse(newTypeData.Resources);
                newTypeData.Resources = {};
                const mainMenus = [];
                const subMenus = [];
                for (const ResourceID of resources) {
                    const subMenuList = await Resource.findOne({ where: { ResourceID: ResourceID } });
                    const mainMenuSubMenu = await MainMenuSubMenu.findOne({ where: { SubMenuID: subMenuList.ResourceID } });
                    console.log(mainMenuSubMenu);
                    if (mainMenuSubMenu) {
                        const mainMenu = await MainMenu.findOne({ where: { MenuID: mainMenuSubMenu.MainMenuID } });
                        if (mainMenu) {
                            const mainMenuInfo = {
                                MainMenuID: mainMenu.MenuID,
                                MainMenuName: mainMenu.MenuName,
                                MainMenuIcon: mainMenu.Icon,
                                MainMenuURL: mainMenu.URL,
                                MainMenuOrder: mainMenu.Order
                            };
                            mainMenus.push(mainMenuInfo);
                        } else {
                            mainMenus = null
                        }
                    }
                    const subMenuInfo = {
                        ResourceID: subMenuList.ResourceID,
                        ResourceName: subMenuList.ResourceName,
                        ResourceType: subMenuList.ResourceType
                    }
                    subMenus.push(subMenuInfo);
                }
                newTypeData.Resources = {
                    mainMenus: mainMenus,
                    subMenus: subMenus
                }
                res.status(200).send({
                    newTypeData,
                    meta: {
                        msg: "编辑成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case 'delete':
                const users = await User.findAll({ where: { UserTypeID: userTypeID } });
                // 将外键设置为 null 或其他适当的值
                await Promise.all(
                    users.map(async (user) =>
                    {
                        user.UserTypeID = null; // 或者设置其他适当的值
                        await user.save();
                    })
                );
                const delData = await UserType.destroy({ where: { UserTypeID: userTypeID } })
                res.status(200).send({
                    meta: {
                        msg: "删除成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case "findAllUserTypeName":
                // 获取所有的权限名
                const userTypeNames = await UserType.findAll({
                    attributes: ['UserTypeName', 'UserTypeID']
                })
                res.status(200).send({
                    data: userTypeNames,
                    meta: {
                        msg: "获取成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            case "findAllUserType":
                const allSubMenus = await Resource.findAll();
                const menuMappings = await MainMenuSubMenu.findAll();
                const menuCategories = {};

                // 初始化 menuCategories，将每个主菜单的键初始化为空数组
                const mainMenuList = await MainMenu.findAll();
                mainMenuList.forEach(mainMenu =>
                {
                    menuCategories[mainMenu.MenuID] = {
                        mainMenuId: mainMenu.MenuID,
                        mainMenuName: mainMenu.MenuName, // 假设主菜单有一个属性 name
                        subMenus: [],
                    };
                });

                // 使用映射表将子菜单分类到主菜单
                menuMappings.forEach(mapping =>
                {
                    const subMenu = allSubMenus.find(subMenu => subMenu.ResourceID === mapping.SubMenuID);

                    if (subMenu) {
                        const mainMenuId = mapping.MainMenuID;
                        menuCategories[mainMenuId].subMenus.push({
                            subMenuId: subMenu.ResourceID,
                            subMenuName: subMenu.ResourceName, // 假设子菜单有一个属性 name
                        });
                    }
                });

                // 将 menuCategories 转换为数组形式
                const categorizedMenus = Object.values(menuCategories);

                res.status(200).send({
                    data: categorizedMenus,
                    meta: {
                        msg: "获取成功",
                        status: 200
                    },
                    sql: getExecutedSql()
                })
                break;
            default:
                break;
        }

    } catch (error) {
        res.status(500).send({ message: 'Internal server error', error: error.message });
    }
}